#!/bin/bash

OS_UBUNTU_1204=ubuntu_12.04
OS_UBUNTU_1204_CODE=precise

OS_UBUNTU_1210=ubuntu_12.10
OS_UBUNTU_1210_CODE=quantal

OS_UBUNTU_1404=ubuntu_14.04
OS_UBUNTU_1404_CODE=trusty

UBUNTU_URL_MIRROR='MIRROR=http://ftp.cuhk.edu.hk/pub/Linux/ubuntu'
UBUNTU_URL_SECURITY_MIRROR='SECURITY_MIRROR=http://ftp.cuhk.edu.hk/pub/Linux/ubuntu'
UBUNTU_HTTP_PROXY_IP='192.168.88.10'
UBUNTU_HTTP_PROXY='http_proxy=http://$UBUNTU_HTTP_PROXY_IP:3142/'


WITH_HTTP_PROXY="no"
NETWORK_CONFIG=network.conf
INSTALL_COMMAND_PREFIX=""

check_http_proxy()
{
	local http_proxy_status=`(ping -c1 $UBUNTU_HTTP_PROXY_IP > /dev/null 2>&1 && echo $?) || echo 1`
	echo "http_proxy_status = $http_proxy_status"
	if [ "$http_proxy_status" = "1" ]; then
		WITH_HTTP_PROXY="no"
		echo "Cannot connect to $UBUNTU_HTTP_PROXY_IP, disable http proxy!"
	fi
}

usage() 
{
cat <<EOF
Usage : $0 OSName Action
OSName : ubuntu_12.04 | ubuntu_12.10 | ubuntu_14.04
Action : install | start | stop | console
EOF
exit 1
}

check_lxc()
{
	local lxc_state=$(which lxc-start > /dev/null 2>&1  && echo $?)
	if [ "x$lxc_state" != "x0" ];then
		echo "Plaese install lxc first"
		echo "You can run 'sudo apt-get install lxc' to install lxc"
		exit
	fi
}


OS_NAME=$1
ACTION=$2
check_lxc
if [ $# -ne 2 ];then
	usage
fi

case $OS_NAME in 
	ubuntu_12.04)
		TEMPLATE=ubuntu
		OS_NAME=$OS_UBUNTU_1204
		OS_CODE=$OS_UBUNTU_1204_CODE
		URL_MIRROR=$UBUNTU_URL_MIRROR
		URL_SECURITY_MIRROR=$UBUNTU_URL_SECURITY_MIRROR
		HTTP_PROXY=$UBUNTU_HTTP_PROXY
		WITH_HTTP_PROXY="yes"
		;;
	ubuntu_12.10)
		TEMPLATE=ubuntu
		OS_NAME=$OS_UBUNTU_1210
		OS_CODE=$OS_UBUNTU_1210_CODE
		;;
	ubuntu_14.04)
		TEMPLATE=ubuntu
		OS_NAME=$OS_UBUNTU_1404
		OS_CODE=$OS_UBUNTU_1404_CODE
		;;
	*)
		echo "ERROR: Unknown operator system type: $OS_NAME"
		usage
		;;
esac

case $ACTION in
	install)
		check_http_proxy
		if [ "x$WITH_HTTP_PROXY" = "xyes" ];then
			INSTALL_COMMAND_PREFIX="$HTTP_PROXY $URL_MIRROR $URL_SECURITY_MIRROR"
		fi
		echo "sudo $INSTALL_COMMAND_PREFIX lxc-create -n $OS_NAME -f $NETWORK_CONFIG -t $TEMPLATE -- -r $OS_CODE"
		sudo $INSTALL_COMMAND_PREFIX lxc-create -n $OS_NAME -f $NETWORK_CONFIG -t $TEMPLATE -- -r $OS_CODE
		;;
	start)
		sudo lxc-start -n $OS_NAME
		;;
	stop)
		sudo lxc-stop -n $OS_NAME
		;;
	console)
		sudo lxc-console -n $OS_NAME
		;;
	*)
		echo "ERROR: Unknown Option : $ACTION"
		usage
		;;
esac
